package com.east.service.staff.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.east.bean.DictionaryItems;
import com.east.bean.Staff;
import com.east.bean.StaffArchive;
import com.east.bean.User;
import com.east.controller.staff.StaffExecl;
import com.east.controller.staff.StaffParameter;
import com.east.controller.staff.echar.Dement;
import com.east.controller.staff.echar.StaffEchar;
import com.east.controller.staff.echar.Statistics;
import com.east.dao.StaffArchiveMapper;
import com.east.dao.StaffMapper;
import com.east.dao.UserMapper;
import com.east.service.staff.StaffService;
import com.east.utils.DateUtils;
import com.east.utils.Pagenation;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

@Service("staffService")
public class StaffServiceImpl implements StaffService{
		@Autowired
		StaffMapper staffMapper;
		@Autowired
		StaffArchiveMapper staffArchiveMapper;
		@Autowired
		UserMapper userMapper;
		@Override
		public Page<Staff> findByAll(Pagenation pagenation, String key, String status) {
			Page<Staff> startPage = PageHelper.startPage(pagenation.getPageNum(), pagenation.getPageSize());
			staffMapper.findStaffArchive(status, key);
			return startPage;
		}

		@Override
		public Staff findByStaff(Staff staff) {
			return staffMapper.findStaff(staff.getsId());
		}
		@Transactional
		@Override
		public int savaStaff(StaffParameter sp) {
			//员工信息
			Staff s = new Staff(); 
			s.setsName(sp.getName());
			s.setsTelephone(sp.getTelephone());
			s.setsOfficePhone(sp.getOfficPhone());
			s.setsEmail(sp.getEmail());
			s.setsUuid(UUID.randomUUID().toString());
			s.setsSerialNum(sp.getSerialNum());
			s.setsDelFlag(1);
			s.setsStatus(sp.getStatus());
			if(StringUtils.isNotBlank(sp.getEntryTime())) {
				s.setsEntryTime(DateUtils.getDate(sp.getEntryTime()));
			}
			if(StringUtils.isNotBlank(sp.getWorking())) {
				s.setsWorking(DateUtils.getDate(sp.getWorking()));
			}
			s.setsPosition(sp.getPosition());
			
			//部门
			s.setDepartmentId(sp.getDid());
			s.setDepartmentName(sp.getDepartmentName());
			//岗位
			s.setsPosition(sp.getPosition());
			s.setDiIds(sp.getdIds());
			 staffMapper.insert(s);
			
			//员工档案信息
			StaffArchive sa = new StaffArchive();
			sa.setStaffId(s.getsId());
			sa.setSaName(sp.getName());
			sa.setSaTelephone(sp.getTelephone());
			sa.setSaOfficePhone(sp.getOfficPhone());
			sa.setSaEmail(sp.getEmail());
			sa.setSaUuid(UUID.randomUUID().toString());
			sa.setSaSerialNum(sp.getSerialNum());
			sa.setSaSex(sp.getSex());
			//新添加字段\\
			sa.setSaAge(sp.getAge());
			sa.setSaProfession(sp.getProfession());
			sa.setSaHouseholdRegister(sp.getHouseholdRegister());
			sa.setSaCardId(sp.getCardId());
			sa.setSaFamilyAddress(sp.getFamilyAddress());
			sa.setSaNativePlace(sp.getNativePlace());
			sa.setSaMaritalStatus(sp.getMaritalStatus());
			sa.setSaNation(sp.getNation());
			sa.setSaEducation(sp.getEducation());
			
			sa.setSaWork(sp.getWork());
			sa.setSaMaster(sp.getMaster());
			staffArchiveMapper.insert(sa);
			User u = new User();
			u.setuPassword(sp.getPassword());
			u.setuStaffId(s.getsId());
			u.setuAccount(sp.getUser());
			u.setuState(1);
			u.setuLoginTime(new Date());
			u.setuPhone(sp.getTelephone());
			return userMapper.insert(u);
		}

		@Override
		public int updateStaff(StaffParameter sp) {
			//员工信息
			Staff s = staffMapper.findStaff(sp.getId());
			s.setsName(sp.getName());
			s.setsTelephone(sp.getTelephone());
			s.setsOfficePhone(sp.getOfficPhone());
			s.setsEmail(sp.getEmail());
			s.setsUuid(UUID.randomUUID().toString());
			s.setsSerialNum(sp.getSerialNum());
			s.setsDelFlag(1);
			s.setsStatus(sp.getStatus());
			if(StringUtils.isNotBlank(sp.getEntryTime())) {
				s.setsEntryTime(DateUtils.getDate(sp.getEntryTime()));
			}
			if(StringUtils.isNotBlank(sp.getWorking())) {
				s.setsWorking(DateUtils.getDate(sp.getWorking()));
			}
			s.setsPosition(sp.getPosition());
			
			//部门
			s.setDepartmentId(sp.getDid());
			s.setDepartmentName(sp.getDepartmentName());
			//岗位
			s.setsPosition(sp.getPosition());
			s.setDiIds(sp.getdIds());
			staffMapper.updateByPrimaryKey(s);
			
			//员工档案信息
			StaffArchive sa = s.getStaffArchive();
			sa.setStaffId(s.getsId());
			sa.setSaName(sp.getName());
			sa.setSaTelephone(sp.getTelephone());
			sa.setSaOfficePhone(sp.getOfficPhone());
			sa.setSaEmail(sp.getEmail());
			sa.setSaUuid(UUID.randomUUID().toString());
			sa.setSaSerialNum(sp.getSerialNum());
			sa.setSaSex(sp.getSex());
			//新添加字段\\
			sa.setSaAge(sp.getAge());
			sa.setSaProfession(sp.getProfession());
			sa.setSaHouseholdRegister(sp.getHouseholdRegister());
			sa.setSaCardId(sp.getCardId());
			sa.setSaFamilyAddress(sp.getFamilyAddress());
			sa.setSaNativePlace(sp.getNativePlace());
			sa.setSaMaritalStatus(sp.getMaritalStatus());
			sa.setSaNation(sp.getNation());
			sa.setSaEducation(sp.getEducation());
			
			sa.setSaWork(sp.getWork());
			sa.setSaMaster(sp.getMaster());
			staffArchiveMapper.updateByPrimaryKey(sa);
			User u = s.getUser();
			u.setuPassword(sp.getPassword());
			u.setuAccount(sp.getUser());
			u.setuLoginTime(new Date());
			u.setuPhone(sp.getTelephone());
			userMapper.updateByPrimaryKey(u);
			return userMapper.updateByPrimaryKey(u);
		}

		@Override
		public int delStaff(Staff staff) {
			Staff selectByPrimaryKey = staffMapper.selectByPrimaryKey(staff.getsId());
			selectByPrimaryKey.setsDelFlag(0);
			return staffMapper.updateByPrimaryKey(selectByPrimaryKey);
		}

		@Override
		public Page<Staff> findByDepartMentId(Pagenation pagenation, Integer dId) {
			Page<Staff> startPage = PageHelper.startPage(pagenation.getPageNum(), pagenation.getPageSize());
			staffMapper.finbyDepartmentdId(dId);
			return startPage;
		}

		@Override
		public Page<StaffExecl> findByTall(Pagenation pagenation, String key, String did,String status) {
			Page<StaffExecl> startPage = PageHelper.startPage(pagenation.getPageNum(), pagenation.getPageSize());
			staffMapper.findStaffArchiveExecl(did, key,status);
			return startPage;
		}

		@Override
		public List<StaffExecl> findByTall(String key, String did,String status) {
			
			return staffMapper.findStaffArchiveExecl(did, key,status);
		}

		@SuppressWarnings("unlikely-arg-type")
		@Override
		public Map<String, Object> findByAge() {
			
			Map<String, Object> maps = new HashMap<String, Object>();
			
			
			List<Statistics> findByStatisticsAge = staffMapper.findByStatisticsAge();
			for (Statistics sta : findByStatisticsAge) {
				if(sta.getAgeRatio()==0) {
					sta.setName("其他");
				}
				if(sta.getAgeRatio()==1) {
					sta.setName("80前");
				}
				if(sta.getAgeRatio()==2) {
					sta.setName("80~85后");
				}
				if(sta.getAgeRatio()==3) {
					sta.setName("85~90后");
				}
				if(sta.getAgeRatio()==4) {
					sta.setName("90~95后");
				}
				if(sta.getAgeRatio()==5) {
					sta.setName("95后");
				}
				if(sta.getAgeRatio()==6) {
					sta.setName("未知");
				}
			}
			maps.put("staffEchar",findByStatisticsAge);
			maps.put("type",new  String[] {"其他","80前","80~85后","85~90后","90~95后","95后","未知"});
			return maps;
		}

		@Override
		public  Map<String, Object> findByPosition() {
			Map<String, Object> maps = new HashMap<String, Object>();
			List<Statistics> findByStatisticsAge = staffMapper.findByStatisticsPosition();
			for (Statistics sta : findByStatisticsAge) {
				if(sta.getAgeRatio()==-1) {
					sta.setName("其他");
				}
				if(sta.getAgeRatio()==1) {
					sta.setName("0年");
				}
				if(sta.getAgeRatio()==2) {
					sta.setName("1~3年");
				}
				if(sta.getAgeRatio()==3) {
					sta.setName("3~5年");
				}
				if(sta.getAgeRatio()==4) {
					sta.setName("5~7年");
				}
				if(sta.getAgeRatio()==5) {
					sta.setName("7年以上");
				}
				if(sta.getAgeRatio()==6) {
					sta.setName("未知");
				}
			}
			maps.put("staffEchar",findByStatisticsAge);
			maps.put("type",new  String[] {"其他","0年","1~3年","3~5年","5~7年","7年以上"});
			return maps;
		}

		@Override
		public  Map<String, Object> findByJob() {
			Map<String, Object> maps = new HashMap<String, Object>();
			List<Statistics> findByStatisticsAge = staffMapper.findByStatisticsEntryTime();
			for (Statistics sta : findByStatisticsAge) {
				if(sta.getAgeRatio()==-1) {
					sta.setName("其他");
				}
				if(sta.getAgeRatio()==1) {
					sta.setName("0年");
				}
				if(sta.getAgeRatio()==2) {
					sta.setName("1~3年");
				}
				if(sta.getAgeRatio()==3) {
					sta.setName("3~5年");
				}
				if(sta.getAgeRatio()==4) {
					sta.setName("5~7年");
				}
				if(sta.getAgeRatio()==5) {
					sta.setName("7年以上");
				}
				if(sta.getAgeRatio()==6) {
					sta.setName("未知");
				}
			}
			maps.put("staffEchar",findByStatisticsAge);
			maps.put("type",new  String[] {"其他","0年","1~3年","3~5年","5~7年","7年以上"});
			return maps;
		}
		@Override
		public Object findByJobDepartMent() {
			
			List<Dement> findByStatisticsAge = staffMapper.findByStatisticsDepartMent();
			/*List<String> name=new ArrayList<String>();
			List<Integer> value=new ArrayList<Integer>();
			for (Statistics stas : findByStatisticsAge) {
				name.add(stas.getName());
				value.add(stas.getValue());
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("type",name.toArray());
			map.put("staffEchar", value.toArray());*/
		return findByStatisticsAge;
		}
	@SuppressWarnings("unchecked")
	@Override
	public void execlSelf(HttpServletRequest request, HttpServletResponse response,String key,String did,String status) {
     // 创建参数对象（用来设定excel得sheet得内容等信息）
        ExportParams params = new ExportParams() ;
        params.setSheetName("人员统计");
        ExportParams paramsage = new ExportParams() ;
        paramsage.setSheetName("年龄统计");
        ExportParams paramsPosition = new ExportParams() ;
        paramsPosition.setSheetName("岗位年限统计");
        ExportParams paramsJob = new ExportParams() ;
        paramsJob.setSheetName("在职年限统计");
        ExportParams paramsDement = new ExportParams() ;
        paramsDement.setSheetName("部门人数统计");
        Map<String, Object> findByAge = findByAge();
        Map<String, Object> findByJob = findByJob();
        Map<String, Object> findByPosition = findByPosition();
        
        
        List<Statistics> age = (List<Statistics>) findByAge.get("staffEchar");
        
        List<Statistics> job = (List<Statistics>) findByJob.get("staffEchar");
        
        List<Statistics> position = (List<Statistics>) findByPosition.get("staffEchar");
        
        List<Dement> findByStatisticsDepartMent = staffMapper.findByStatisticsDepartMent();
        // 创建sheet1使用得map
        Map<String,Object> dataMap1 = new HashMap<>();
        // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
        dataMap1.put("title",params) ;
        // 模版导出对应得实体类型
        dataMap1.put("entity",StaffExecl.class) ;
        // sheet中要填充得数据
        dataMap1.put("data",staffMapper.findStaffArchiveExecl(did, key, status)) ;
        // 创建sheet2使用得map
        Map<String,Object> dataMap2 = new HashMap<>();
        dataMap2.put("title",paramsage) ;
        dataMap2.put("entity",Statistics.class) ;
        dataMap2.put("data",age) ;
        
        
        
        Map<String,Object> dataMap3 = new HashMap<>();
        dataMap3.put("title",paramsPosition) ;
        dataMap3.put("entity",Statistics.class) ;
        dataMap3.put("data",position) ;
        
        Map<String,Object> dataMap4 = new HashMap<>();
        dataMap4.put("title",paramsJob) ;
        dataMap4.put("entity",Statistics.class) ;
        dataMap4.put("data",job) ;
        Map<String,Object> dataMap5 = new HashMap<>();
        dataMap5.put("title",paramsDement) ;
        dataMap5.put("entity",Dement.class) ;
        dataMap5.put("data",findByStatisticsDepartMent) ;
        
        // 将sheet1和sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>() ;
        sheetsList.add(dataMap1);
        sheetsList.add(dataMap5);
        sheetsList.add(dataMap2);
        sheetsList.add(dataMap3);
        sheetsList.add(dataMap4);
        
        Workbook exportBigExcel = ExcelExportUtil.exportExcel(sheetsList,  ExcelType.HSSF);
		  try {
	        	String fileName = "人员统计" + "_" +".xls";
	            OutputStream output = null;
	            response.reset();  
	            response.setContentType("application/vnd.ms-excel; charset=utf-8");
	            response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode(fileName , "UTF-8"));
	            response.setCharacterEncoding("utf-8");  
	            output = response.getOutputStream();
	            exportBigExcel.write(output);  
	            output.flush();
	            output.close();
	            System.out.println("导出成功!");
	        } catch (FileNotFoundException e) {
	            System.out.println("导出失败!");
	            e.printStackTrace();
	        } catch (IOException e) {
	            System.out.println("导出失败!");
	            e.printStackTrace();
	        }

	}
		
		
	
		
}
